package com.eliansun.util;

import com.alibaba.fastjson.JSONException;
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
import com.gargoylesoftware.htmlunit.WebClient;
import org.apache.log4j.Logger;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 * Created by ljh on 2017/5/4.
 */
public class HtmlUnitDriverProxy {
    private static final Logger logger = Logger.getLogger(HtmlUnitDriverProxy.class);
    // 代理隧道验证信息
    final static String proxyUser = "HCKGE862P7VWM3DP";
    final static String proxyPass = "D73093579AA1DFEC";
    // 代理服务器
    final static String proxyServer = "http-pro.abuyun.com:9010";

    public static HtmlUnitDriver getHtmlUnitDriver()
    {
        HtmlUnitDriver driver = null;

        Proxy proxy = new Proxy();
        // 设置代理服务器地址
        proxy.setHttpProxy(proxyServer);

        DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
        capabilities.setCapability(CapabilityType.PROXY, proxy);
        capabilities.setJavascriptEnabled(true);
        capabilities.setPlatform(Platform.WIN8_1);

        driver = new HtmlUnitDriver(capabilities) {
            @Override
            protected WebClient modifyWebClient(WebClient client) {
                DefaultCredentialsProvider creds = new DefaultCredentialsProvider();
                creds.addCredentials(proxyUser, proxyPass);
                client.setCredentialsProvider(creds);
                return client;
            }
        };

        driver.setJavascriptEnabled(true);

        return driver;
    }

    public static void main(String[] args) throws JSONException
    {
        HtmlUnitDriver driver = getHtmlUnitDriver();

        driver.get("https://maiyao.liangxinyao.com/search.htm?type=p&search=y&newHeader_b=s_from&searcy_type=item&from=liangxinyao.shop.pc_1_placeholder&spm=a1z10.3-b-s.a2227oh.d101&pageNo=1&tsearch=y#anchor");

        System.out.println(driver.getPageSource());
    }

}
